import { removeToken, removeUserInfo } from "@/utils/auth.js";
import vue from "vue";

import { loginByWx, getUserInfo } from "../../api/user.js";
import {
  saveToken,
  saveUserId,
  saveShiroToken,
  saveUserInfo,
  saveMobile,
  getUserInfoByStorage,
  getMobile,
} from "../../utils/auth.js";
import local from "../../store/local";
const api = require("@/api/api.js").api;

const defaultUserInfo = {
  id: "",
  isLandlord: false,
  lastLoginIp: "",
  lastLoginTime: "",
  mobile: "",
  mpOpenId: null,
  nickname: "",
  openId: "",
  password: "",
  qqOpenId: null,
  registerIp: "",
  registerTime: "",
  signAllIntegral: 0,
  signUsedIntegral: 0,
  subscribe: 0,
  subscribeTime: null,
  unionId: null,
  userLevelId: "1",
  userLevelName: "青铜",
  userName: "",
  headImgUrl: "",
  userId: "",
};

console.log(getUserInfoByStorage());
export default {
  state: {
    /**
     * 是否需要强制登录
     */
    forcedLogin: true,
    hasLogin: false,
    userInfo: Object.assign({}, getUserInfoByStorage()),
    messageList: [],
    roles: ["admin"],
    wxCode: "",
    tagSignTemp: "",
    tempUserInfo: {},
    mobile: "",
  },
  mutations: {
    RESET_STATE(state, initialState) {
      // 使用 Object.assign 替换整个 state
      Object.assign(state, initialState);
    },

    SET_TAG_SIGN_TEMP(state, tagSignTemp) {
      // 设置临时签名
      state.tagSignTemp = tagSignTemp;
    },

    SET_LOGIN(state, hasLogin) {
      // 设置登录状态
      state.hasLogin = hasLogin;
    },
    SET_USERINFO(state, info) {
      console.log(info);
      // 设置用户信息
      state.userInfo = Object.assign({}, defaultUserInfo, info);
      saveUserInfo(info);
    },
    SET_MOBILE(state, mobile) {
      state.mobile = mobile;
    },
    SET_MESSAGE(state, list) {
      // 设置消息列表
      state.messageList = list;
    },
    SET_WXCODE(state, code) {
      // 保存微信code
      state.wxCode = code;
    },
    SET_TEMP_USERINFO(state, tempUserInfo) {
      state.tempUserInfo = tempUserInfo;
    },
    // SET_MAIL_LIST(state, list) {
    // 	state.mailList = list;
    // }
  },
  actions: {
    checkSession({ commit, dispatch }, data) {
      console.log(dispatch);
      return new Promise((resolve, reject) => {
        uni.checkSession({
          success() {
            console.log("session ok");
          },
          fail: (res) => {
            console.log("session bad");
            dispatch("login");
          },
        });
      });
    },
    login({ commit, dispatch }, data) {
      return new Promise((resolve, reject) => {
        console.log("login ing");
        uni.login({
          success: (loginRes) => {
            console.log(loginRes);
            let { errMsg, code } = loginRes;
            if (code) {
              commit("SET_WXCODE", code);
            }
          },
          fail(res) {
            console.error(res, "fail login");
          },
        });
      });
    },

    loginByAllMin({ state, commit, dispatch }, userInfo) {
      // 通过微信登录
      console.log("loginByAllMin");
      return new Promise((resolve, reject) => {
        let params = {
          code: state.wxCode,
        };

        let token = state.tempUserInfo.token;
        let userId = state.tempUserInfo.userId;
        params.encryptedData = userInfo.encryptedData;
        params.iv = userInfo.iv;
        params.signature = userInfo.signature;
        params.changeToken = token;
        // console.log("loginByAllMin",params,state.tempUserInfo)

        // console.log(JSON.stringify(params),"loginUser")

        // return
        api.user
          .saveThirdBaseInfo(params)
          .then((res) => {
            let openId = res.data;
            // console.error("loginUserafter",res.data,res.data.bind)
            if (token && openId && shrioToken) {
              //设置首页刷新
              local.setIndexAfterLoginRefeshed(false);
              local.setUserAfterLoginRefeshed(false);

              // 登陆成功
              commit("SET_LOGIN", true);
              saveToken(token);
              saveUserId(userId);

              saveShiroToken(shrioToken);
              dispatch("getUserInfo");
              // getApp().connentRongIM();
              local.setOpenId(openId);
            }
            resolve(res);
          })
          .catch((res) => {
            reject(res);
          });

        dispatch("login");
      });
    },
    // 登出
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        commit("SET_LOGIN", false);
        commit("SET_USERINFO", false);
        removeToken();
        removeUserInfo();
        resolve();
        local.setOwnerToken(false);
        local.setOwnerUserId(false);
        local.setImToken(null);
        // getApp().globalData.im.disconnect().then(function() {
        //   console.log('断开链接成功');
        // });
      });
    },
    getUserInfo({ commit, dispatch, state }, data) {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          const { data } = res;
          console.log(dispatch + "这里获取user信息");
          commit("SET_USERINFO", { ...data });
        });
      });
    },
    getMessage({ commit, dispatch }, data) {
      return new Promise((resolve, reject) => {
        vue.prototype.$api.user.getMessage().then((res) => {
          const { data } = res;
          commit("SET_MESSAGE", data);
        });
      });
    },
  },
  getters: {
    forcedLogin: (state) => state.forcedLogin,
    // mailList: state => state.mailList,
    userInfo: (state) => state.userInfo,
    messageList: (state) => state.messageList,
    mobile: (state) => state.mobile,
    messageCount: (state) => state.messageList.length,
    tagSignTemp: (state) => state.tagSignTemp,
    wxCode: (state) => state.wxCode,
    tempUserInfo: (state) => state.tempUserInfo,
  },
};
